import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
import 'package:state_management_redux/contactor/contactor_page.dart';
import 'package:state_management_redux/to_do_list/middleware.dart';
import 'package:state_management_redux/to_do_list/reducers.dart';
import 'package:state_management_redux/to_do_list/state.dart';
import 'package:state_management_redux/to_do_list/to_do_list_page.dart';

import 'counter/counter_page.dart';
import 'shopping_list/shopping_list_action.dart';
import 'shopping_list/shopping_list_home.dart';
import 'shopping_list/shopping_list_middleware.dart';
import 'shopping_list/shopping_list_reducer.dart';
import 'shopping_list/shopping_list_state.dart';
import 'utils/cookie_manager.dart';

void main() {
  runApp(MainApp());
  CookieManager.instance.initCookie();
}

// 根据需要切换应用示例
// CounterPage
// ContactorPage：联系人示例
// ToDoListPage：待办事项清单
// ShoppingListHome：购物清单
// DynamicDetailWrapper：局部刷新
class MainApp extends StatelessWidget {
  MainApp({Key? key}) : super(key: key);
  // distinct = true，状态不变不刷新；distinct = false：只要有 action 就会刷新
  final store = Store<ShoppingListState>(
    shoppingListReducer,
    initialState: ShoppingListState.initial(),
    middleware: shopplingListMiddleware(),
    distinct: true,
  );
  @override
  Widget build(BuildContext context) {
    return StoreProvider<ShoppingListState>(
      store: store,
      child: MaterialApp(
        title: 'Redux Demo',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: StoreBuilder<ShoppingListState>(
          onInit: (store) => store.dispatch(ReadOfflineAction()),
          builder: (context, store) => ShoppingListHome(),
        ),
        builder: EasyLoading.init(),
      ),
    );
  }
}

class ToDoListApp extends StatelessWidget {
  final Store<AppState> store = Store<AppState>(
    appReducer,
    initialState: AppState.initial(),
    middleware: createStoreMiddleware(),
  );

  @override
  Widget build(BuildContext context) => StoreProvider(
        store: this.store,
        child: MaterialApp(
          title: 'Redux Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          home: ToDoListPage(),
        ),
      );
}
